package com.fancy.application.tools.code.generate.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fancy.application.common.service.impl.BaseService;
import com.fancy.application.tools.code.generate.entity.CodeGenerateModuleInfo;
import com.fancy.application.tools.code.generate.entity.CodeGenerateTableInfo;
import com.fancy.application.tools.code.generate.mapper.CodeGenerateModuleInfoMapper;
import com.fancy.application.tools.code.generate.service.ICodeGenerateModuleInfoService;
import com.fancy.application.tools.code.generate.service.ICodeGenerateTableInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;


@Service("codeGenerateModuleInfoService")
public class CodeGenerateModuleInfoServiceImpl extends BaseService<CodeGenerateModuleInfoMapper, CodeGenerateModuleInfo> implements ICodeGenerateModuleInfoService {
    @Override
    /**
     * 创建目录
     * @param fdModuleId
     * @Return 目录路径
     */
    public String getDirPath(String fdMoudleId) {
        CodeGenerateModuleInfo moduleInfo = this.getById(fdMoudleId);
        String modulePath = moduleInfo.getFdModulePath();
        return StrUtil.replace(modulePath,".", File.separator);
    }

    @Override
    public void generateCodeByModuleId(String id) {
        CodeGenerateModuleInfo moduleInfo = this.getById(id);
        List<CodeGenerateTableInfo> tableInfoList = codeGenerateTableInfoService.list(new QueryWrapper<CodeGenerateTableInfo>().eq("fd_module_id",id));
        /**
         * 此处不处理js
         * js需要合并成一个文件.
         * 后期考虑sql也要合并在一个文件
         */
        tableInfoList.forEach(codeGenerateTableInfo -> codeGenerateTableInfoService.generateCodeByTableId(codeGenerateTableInfo.getFdId()));
        codeGenerateTableInfoService.generateJsCodeByTables(moduleInfo,tableInfoList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteModuleById(String id) {
        //CodeGenerateModuleInfo moduleInfo = this.getById(id);
        List<CodeGenerateTableInfo> tableInfoList = codeGenerateTableInfoService.list(new QueryWrapper<CodeGenerateTableInfo>().eq("fd_module_id",id));
        tableInfoList.forEach(codeGenerateTableInfo -> codeGenerateTableInfoService.deleteTableById(codeGenerateTableInfo.getFdId()));
        this.removeById(id);
    }


    @Resource
    private ICodeGenerateTableInfoService codeGenerateTableInfoService;
//    @Resource
//    private CodeGenerateCoreServiceImpl codeGenerateCoreService;
}
